【今日湯底】
The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
Examples
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
Notes
Assertion messages may be unclear about what they display in some languages. If you read "...It Should encode XXX", the "XXX" is the expected result, not the input!
(必須通過以下測試)
(ns kata.test
(:require [clojure.test :refer :all]))
(defn dotest [text expected]
(is (= (kata.core/encode-dups text) expected)))
(deftest sample
(testing "basic"
(dotest "din" "(((")
(dotest "recede" "()()()")
(dotest "(( @" "))((")
(dotest "ABC" "(((")
(dotest "AaBbC" "))))(")
)
(testing "ignore-case" (dotest "Success" ")())())"))
)
【我的答案】
(ns kata.core)
(defn encode-dups [text]
(let [lowered-text (clojure.string/lower-case text)
freqen (frequencies lowered-text)]
(->> lowered-text
(map #(if (= 1 (freqen %)) "(" ")"))
(clojure.string/join "")))
)
有找到 frequencies
但卡在怎麼把 map value 為 1 -> "(" 非 1 -> ")" 然後再用 replace 去處理,卡太久就先看答案學習了XD
後來再試著寫,目前還是 not all pass QQ
(ns kata.core)
(defn encode-dups [text]
(let [lowered (clojure.string/lower-case text)]
(clojure.string/replace lowered #"\S" (reduce merge (map (fn [[k v]] (if (= v 1) {(str k) "("} {(str k) ")"})) (frequencies lowered)))))
)
【其他人的答案】
(ns kata.core
(:require [clojure.string :as str]))
(defn encode-dups [text]
(let [lowered (str/lower-case text)
number-of-times (frequencies lowered)]
(->> lowered
(map #(if (= 1 (number-of-times %1)) "(" ")"))
(str/join))))
(ns kata.core)
(defn encode-dups [text]
(let [lower-text (clojure.string/lower-case text)
char-map (->> lower-text
frequencies
(map (fn [[k v]] (if (= v 1) {k "("} {k ")"})))
(reduce merge {}))]
(->> lower-text (map char-map) clojure.string/join)))